<template>
  <div>
    <div id="map-container" style="height: 500px;"></div>
    <div class="control-panel">
      <div class="operation-bar">
        <el-button 
          size="small" 
          type="primary" 
          icon="el-icon-refresh" 
          @click="refreshList"
          :loading="loading">
          刷新
        </el-button>
        <el-input
          v-model="searchQuery"
          placeholder="输入物流单号搜索"
          style="width: 200px; margin-left: 10px;"
          size="small"
          clearable
          @clear="getLogisticsList"
          @keyup.enter.native="getLogisticsList">
          <el-button 
            slot="append" 
            icon="el-icon-search" 
            @click="getLogisticsList">
          </el-button>
        </el-input>
      </div>

      <el-table 
        :data="logisticsList" 
        style="width: 100%"
        v-loading="loading">
        <el-table-column prop="trackingNumber" label="物流单号"></el-table-column>
        <el-table-column prop="carrierName" label="物流公司"></el-table-column>
        <el-table-column prop="startaddress" label="起点"></el-table-column>
        <el-table-column prop="deliveryAddress" label="配送地址"></el-table-column>
        <el-table-column prop="consigneeName" label="收货人"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ statusMap[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.status === '0'"
              size="small" 
              type="success"
              @click="startDelivery(scope.row.trackingNumber)">
              开始配送
            </el-button>
            <el-button 
              v-if="scope.row.status === '1'"
              size="small" 
              type="primary"
              @click="trackDelivery(scope.row)">
              跟踪配送
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      map: null,
      marker: null,
      polyline: null,
      locationTimer: null,
      points: [],
      logisticsList: [],
      loading: false,
      searchQuery: '',
      statusMap: {
        '0': '等待配送',
        '1': '配送中',
        '2': '已签收'
      }
    }
  },

  mounted() {
    this.initMap();
    this.getLogisticsList();
  },

  methods: {
    initMap() {
      this.map = new BMap.Map("map-container");
      const point = new BMap.Point(118.861806, 32.069432);
      this.map.centerAndZoom(point, 14);
      this.map.addControl(new BMap.NavigationControl());
      this.map.addControl(new BMap.ScaleControl());
      this.map.enableScrollWheelZoom();
    },

    async getLogisticsList() {
      try {
        this.loading = true;
        const resp = await this.$axios.get('/apib/api/track/list', {
          params: { searchQuery: this.searchQuery }
        });
        if (resp.data.code === 200) {
          this.logisticsList = resp.data.data;
        } else {
          this.$message.error(resp.data.msg || '获取物流单列表失败');
        }
      } catch (error) {
        console.error('获取物流单列表失败:', error);
        this.$message.error('获取物流单列表失败');
      } finally {
        this.loading = false;
      }
    },

    getStatusType(status) {
      const typeMap = {
        '0': 'info',
        '1': 'warning',
        '2': 'success'
      };
      return typeMap[status] || 'info';
    },

    refreshList() {
      this.getLogisticsList();
    },

    async startDelivery(trackingNumber) {
      try {
        const resp = await this.$axios.get(`/apib/api/track/startDelivery/${trackingNumber}`);
        if (resp.data.code === 200) {
          this.$message.success('开始配送');
          const logistics = this.logisticsList.find(item => item.trackingNumber === trackingNumber);
          if (logistics) {
            this.stopLocationUpdate();
            this.points = [];
            this.map.clearOverlays();
            
            const startPoint = new BMap.Point(logistics.startlng, logistics.startlat);
            const endPoint = new BMap.Point(logistics.endlng, logistics.endlat);
            this.addMapMarkers(startPoint, endPoint);
          }
          this.startLocationUpdate(trackingNumber);
        }
      } catch (error) {
        this.$message.error('开始配送失败');
      }
    },

    trackDelivery(logistics) {
      this.stopLocationUpdate();
      this.points = [];
      this.map.clearOverlays();
      
      const startPoint = new BMap.Point(logistics.startlng, logistics.startlat);
      const endPoint = new BMap.Point(logistics.endlng, logistics.endlat);
      
      this.addMapMarkers(startPoint, endPoint);
      this.startLocationUpdate(logistics.trackingNumber);
    },

    addMapMarkers(startPoint, endPoint) {
      const startMarker = new BMap.Marker(startPoint);
      const endMarker = new BMap.Marker(endPoint);
      this.marker = new BMap.Marker(startPoint);
      
      this.map.addOverlay(startMarker);
      this.map.addOverlay(endMarker);
      this.map.addOverlay(this.marker);
      this.map.setViewport([startPoint, endPoint]);
    },

    startLocationUpdate(trackingNumber) {
      this.stopLocationUpdate();
      
      this.points = [];
      if (this.polyline) {
        this.map.removeOverlay(this.polyline);
        this.polyline = null;
      }
      
      this.locationTimer = setInterval(async () => {
        try {
          const resp = await this.$axios.get(`/apib/api/track/getLocation/${trackingNumber}`);
          if (resp.data.code === 200 && resp.data.data) {
            const location = resp.data.data;
            console.log('获取到新位置:', location);
            
            if (location.lng && location.lat) {
              this.updateDeliveryStatus(location);
              
              if (location.status === '2') {
                this.stopLocationUpdate();
                this.$message.success('配送完成');
                this.refreshList();
              }
            }
          }
        } catch (error) {
          console.error('获取位置失败:', error);
        }
      }, 1000);
    },

    updateDeliveryStatus(location) {
      const lng = parseFloat(location.lng);
      const lat = parseFloat(location.lat);
      
      if (isNaN(lng) || isNaN(lat)) {
        console.error('无效的坐标:', location);
        return;
      }
      
      const point = new BMap.Point(lng, lat);
      
      if (!this.marker) {
        this.marker = new BMap.Marker(point);
        this.map.addOverlay(this.marker);
      } else {
        this.marker.setPosition(point);
      }
      
      this.points.push(point);
      
      if (this.points.length > 1) {
        if (this.polyline) {
          this.map.removeOverlay(this.polyline);
        }
        
        this.polyline = new BMap.Polyline(this.points, {
          strokeColor: "blue",
          strokeWeight: 3,
          strokeOpacity: 0.8
        });
        this.map.addOverlay(this.polyline);
      }
      
      this.map.panTo(point);
      
      console.log('更新位置:', lng, lat);
      console.log('轨迹点数量:', this.points.length);
    },

    stopLocationUpdate() {
      if (this.locationTimer) {
        clearInterval(this.locationTimer);
        this.locationTimer = null;
      }
    },

    async getLocation(trackingNumber) {
      try {
        const resp = await this.$axios.get(`/apib/api/track/getLocation/${trackingNumber}`);
        if (resp.data.code === 200) {
          const location = resp.data.data;
          this.updateMarkerPosition(location);
          
          if (location.status === '2') {
            this.stopLocationUpdate();
            this.$message.success('配送完成');
          }
        }
      } catch (error) {
        console.error('获取位置失败:', error);
      }
    },

    async stopDelivery(trackingNumber) {
      try {
        const resp = await this.$axios.get(`/apib/api/track/stopDelivery/${trackingNumber}`);
        if (resp.data.code === 200) {
          this.$message.success('已停止配送');
          this.stopLocationUpdate();
        }
      } catch (error) {
        this.$message.error('停止配送失败');
      }
    }
  },

  beforeDestroy() {
    this.stopLocationUpdate();
  }
}
</script>

<style scoped>
.control-panel {
  margin-top: 10px;
  padding: 10px;
}

.operation-bar {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
</style> 